﻿using Cyss.Core.Api.JWT;
using Cyss.Core.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Api
{
    public class WebApiWorkContext : IWorkContext
    {
        /// <summary>
        /// 登录账户
        /// </summary>
        private AuthenticationUser _AccountUser;
        private IHttpContextAccessor _httpContextAccessor;
        public WebApiWorkContext(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public AuthenticationUser User
        {
            get
            {

                if (_AccountUser == null)
                {
                    var tokenobj = _httpContextAccessor.HttpContext.Request.Headers["ApiToken"];
                    if (tokenobj.Count <= 0)
                    {
                        throw new Exception("登录验证失败");
                    }
                    string token = tokenobj[0];
                    if (string.IsNullOrWhiteSpace(token))
                    {
                        throw new Exception("登录验证失败");
                    }
                    var tokenHelper = IOCEngine.Resolve<ITokenHelper>();
                    string userId = "";
                    string userName = "";
                    //验证jwt,同时取出来jwt里边的用户ID
                    //tokenHelper.GetTokenUser(token, ref userId, ref userName);

                    if (string.IsNullOrWhiteSpace(userId))
                    {
                        throw new Exception("登录验证失败");
                    }

                    _AccountUser = new AuthenticationUser();
                    _AccountUser.Id = int.Parse(userId);
                    _AccountUser.Name = userName;
                }
                return _AccountUser;
            }
            set { }
        }
        public string LoginToken { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    }
}
